<?php

namespace addons\oil\controller;


use addons\sum\model\User as UserModel;
use \addons\oil\model\Order as OrderModel;
use app\admin\model\sum\trade\Order as TradeOrderModel;
use app\common\library\Auth;
use think\Db;
use \app\admin\model\oil\Invoice as InvoiceModel;
use think\Exception;

class Invoice extends Base
{

    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * 重发发票
     * @return void
     */
    public function resend(){
        $user = UserModel::info();
        $params = $this->request->post();
        $id=$params['id'];
        $invoice =InvoiceModel::where('user_id', $user->id)->where('id', $id)->find();
        if(!$invoice){
            $this->error('发票记录不存在');
        }
        if(!isset($params['email'])){
            $this->error('请输入发送邮箱');
        }
        $invoicedata['email']=$params['email'];
        $invoicedata['is_need_send']=1;
        InvoiceModel::where('id',$id)->update($invoicedata);
        $this->success('重发成功');
    }

    /**
     * 重开发票
     * @return void
     */
    public function recreate()
    {
        $user = UserModel::info();
        $params = $this->request->post();
        $this->oilValidate($params, get_class(), 'recreateInvoice');
        extract($params);
        $invoice =InvoiceModel::where('user_id', $user->id)->where('id', $id)->find();
        if(!$invoice){
            $this->error('发票记录不存在');
        }
        if($invoice['re_times']>=1){
            $this->error('该发票所包含订单已经重新开过发票，无法再次申请开票');
        }
        Db::startTrans();
        try {
            $invoicedata=[
                'header_type'=>$header_type,
                'header_title'=>$header_title,
                'header_num'=>$header_num,
                're_times'=>$invoice['re_times']+1,
            ];
            if(isset($company_address)){
                $invoicedata['company_address']=$company_address;
            }
            if(isset($company_phone)){
                $invoicedata['company_phone']=$company_phone;
            }
            if(isset($company_bank)){
                $invoicedata['company_bank']=$company_bank;
            }
            if(isset($company_bank_num)){
                $invoicedata['company_bank_num']=$company_bank_num;
            }
            if(isset($memo)){
                $invoicedata['memo']=$memo;
            }
            if(isset($phone)){
                $invoicedata['phone']=$phone;
            }
            if(isset($email)){
                $invoicedata['email']=$email;
                $invoicedata['is_need_send']=1;
            }else{
                $invoicedata['is_need_send']=0;
            }
            $invoicedata['status']='again';
            InvoiceModel::where('id',$id)->update($invoicedata);
            Db::commit();
            $this->success('重开成功');
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    /**
     * 开票详情
     * @return void
     */
    public function detail()
    {
        $user = UserModel::info();
        $id=$this->request->request('id');
        $invoice =InvoiceModel::where('user_id', $user->id)->where('id', $id)->find();
        $invoice['image']=cdnurl($invoice['image'],true);
        $this->success('操作成功',$invoice);
    }
    /**
     * 开票记录
     * @return void
     */
    public function index()
    {
        $user = UserModel::info();
        $params = $this->request->post();
        $invoices =InvoiceModel::where('user_id', $user->id)->order('id', 'desc')->paginate(10);
        $invoices->each(function ($invoice){
            $invoice['image']=cdnurl($invoice['image'],true);
        });
        $this->success('操作成功',$invoices);
    }
    /**
     * 申请开票
     * @return void
     */
    public function create()
    {
        $user = UserModel::info();
        $params = $this->request->post();
        $this->oilValidate($params, get_class(), 'createInvoice');
        extract($params);
        $orders=new TradeOrderModel();
        $orders = $orders->where('user_id', $user->id)->where('status','in',['paid','completed'])->where('id','in',$order_ids);
        $orders = $orders->where('invoice_status',0)->where('pay_fee','>',0);

        $orders=$orders->paginate(1000);
        if($orders->total()==0){
            $this->error('订单不存在或已开票');
        }
        $invoice_money=0;
        $order_array=[];
        $orders->each(function ($order)use ($type,&$order_array,&$invoice_money){
            $order_item['invoice_money']=$order['pay_fee'];
            $order_item['title']='油品费';
            $invoice_money+=$order_item['invoice_money'];
            $order_item['createtime']=date('Y-m-d H:i:s', $order['createtime']);
            $order_item['order_sn']=$order['order_sn'];
            $order_array[]=$order_item;
        });
        $company_address=isset($company_address)?$company_address:'';
        $company_phone=isset($company_phone)?$company_phone:'';
        $company_bank=isset($company_bank)?$company_bank:'';
        $company_bank_num=isset($company_bank_num)?$company_bank_num:'';
        $memo=isset($memo)?$memo:'';
        $phone=isset($phone)?$phone:'';
        $email=isset($email)?$email:'';
        $is_need_send=0;
        if($email){
            $is_need_send=1;
        }
        Db::startTrans();
        try {
            $title='油品费发票';
            $content=isset($content)?$content:'车用汽油/柴油';
            TradeOrderModel::where('user_id', $user->id)->where('status','in',['paid','completed'])->where('id','in',$order_ids)->update(['invoice_status'=>1]);

            $invoicedata=[
                'user_id'=>$user['id'],
                'type'=>$type,
                'title'=>$title,
                'money'=>$invoice_money,
                'header_type'=>$header_type,
                'header_title'=>$header_title,
                'header_num'=>$header_num,
                'content'=>$content,
                'company_address'=>$company_address,
                'company_phone'=>$company_phone,
                'company_bank'=>$company_bank,
                'company_bank_num'=>$company_bank_num,
                'memo'=>$memo,
                'phone'=>$phone,
                'email'=>$email,
                're_times'=>0,
                'is_need_send'=>$is_need_send,
                'order_ids'=>$order_ids,
                'order_array'=>json_encode($order_array),
                'status'=>'normal',
                'createtime'=>time(),
                'updatetime'=>time()
            ];
            InvoiceModel::insertGetId($invoicedata);
            Db::commit();
            $this->success('申请成功');
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    //这个是之前油站的开票-新的为充值订单的开票
    public function create_old()
    {
        $user = UserModel::info();
        $params = $this->request->post();
        $this->oilValidate($params, get_class(), 'createInvoice');
        extract($params);
        $orders=new OrderModel();
        $orders = $orders->where('user_id', $user->id)->where('status',2)->where('id','in',$order_ids);
        if($type=='1'){//油品费
            $orders = $orders->where('goods_invoice_status',0)->where('total_amount','>',0);
        }elseif($type=='2'){//服务费
            $orders = $orders->where('service_invoice_status',0)->where('dispatch_amount','>',0);
        }
        $orders=$orders->paginate(1000);
        if($orders->total()==0){
            $this->error('订单不存在或已开票');
        }
        $invoice_money=0;
        $order_array=[];
        $orders->each(function ($order)use ($type,&$order_array,&$invoice_money){
            if($type==1){//油品费
                $order_item['invoice_money']=$order['total_amount'];
                $order_item['title']='油品费';
            }elseif($type==2){//服务费
                $order_item['invoice_money']=$order['dispatch_amount'];
                $order_item['title']='服务费';
            }
            $invoice_money+=$order_item['invoice_money'];
            $order_item['createtime']=date('Y-m-d H:i:s', $order['createtime']);
            $order_item['store_name']=$order['store_name'];
            $order_item['fuel_name']=$order['fuel_name'];
            $order_item['litre']=$order['litre'];
            $order_item['order_sn']=$order['order_sn'];
            $order_array[]=$order_item;
        });
        $company_address=isset($company_address)?$company_address:'';
        $company_phone=isset($company_phone)?$company_phone:'';
        $company_bank=isset($company_bank)?$company_bank:'';
        $company_bank_num=isset($company_bank_num)?$company_bank_num:'';
        $memo=isset($memo)?$memo:'';
        $phone=isset($phone)?$phone:'';
        $email=isset($email)?$email:'';
        $is_need_send=0;
        if($email){
            $is_need_send=1;
        }
        Db::startTrans();
        try {
            if($type==1){//油品费
                $title='油品费发票';
                $content=isset($content)?$content:'车用汽油/柴油';
                OrderModel::where('user_id', $user->id)->where('status',2)->where('id','in',$order_ids)->update(['goods_invoice_status'=>1]);
            }elseif($type==2){//服务费
                $title='服务费发票';
                $content=isset($content)?$content:'现代服务*服务费';
                OrderModel::where('user_id', $user->id)->where('status',2)->where('id','in',$order_ids)->update(['service_invoice_status'=>1]);
            }
            $invoicedata=[
                'user_id'=>$user['id'],
                'type'=>$type,
                'title'=>$title,
                'money'=>$invoice_money,
                'header_type'=>$header_type,
                'header_title'=>$header_title,
                'header_num'=>$header_num,
                'content'=>$content,
                'company_address'=>$company_address,
                'company_phone'=>$company_phone,
                'company_bank'=>$company_bank,
                'company_bank_num'=>$company_bank_num,
                'memo'=>$memo,
                'phone'=>$phone,
                'email'=>$email,
                're_times'=>0,
                'is_need_send'=>$is_need_send,
                'order_ids'=>$order_ids,
                'order_array'=>json_encode($order_array),
                'status'=>'normal',
                'createtime'=>time(),
                'updatetime'=>time()
            ];
            InvoiceModel::insertGetId($invoicedata);
            Db::commit();
            $this->success('申请成功');
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    /**
     * 可开发票订单
     * @return void
     */
    public function orderList()
    {
        $user = UserModel::info();
        $date=$this->request->request('date');
        $type=$this->request->request('type',1);
        if(isset($date)){
            $date=urldecode($date);
        }
        $date = isset($date) ? explode('/', $date) : [];
//        if($type==1){//油品费
//            $orders = OrderModel::where('user_id', $user->id)->where('status',2);
//            $orders = $orders->where('goods_invoice_status',0)->where('total_amount','>',0);
//        }elseif($type==2){//服务费
//            $orders = OrderModel::where('user_id', $user->id)->where('status',2);
//            $orders = $orders->where('service_invoice_status',0)->where('dispatch_amount','>',0);
//        }
        $orders = TradeOrderModel::where('user_id', $user->id)->where('status','in',['paid','completed'])->where('invoice_status',0)->where('pay_fee','>',0);
        if($date){
            $start = $date[0] ? strtotime($date[0]) : strtotime(date('Y-m') . '-01');
            $end = $date[1] ? (strtotime($date[1]) + 86399) : strtotime(date('Y-m-d')) + 86399;
            $orders = $orders->whereBetween('createtime', [$start, $end]);
        }

        $orders = $orders->paginate(10);
        $orders->each(function ($order)use ($type){
//            if($type==1){//油品费
//                $order['invoice_money']=$order['total_amount'];
//            }elseif($type==2){//服务费
//                $order['invoice_money']=$order['dispatch_amount'];
//            }
            $order['invoice_money']=$order['pay_fee'];
        });
        $this->success('获取成功',$orders);
    }


}
